package algo;

public class StringCompression_443 {
    public int compress(char[] chars) {
        int i = 0, l = 0, r = 0;
        int n = chars.length;
        while (r < n) {
            while (r < n && chars[l] == chars[r]) r++;
            chars[i] = chars[l];
            i++;
            if (r - l > 1) {
                int bits = setLen(chars, r - l, i);
                i += bits;
            }
            l = r;
        }
        return i;

    }

    private int setLen(char[] chars, int count, int i) {
        int start = i;
        while (count > 0) {
            chars[i] = (char) (count % 10 + '0');
            count /= 10;
            i++;
        }
        reverse(chars, start, i - 1);
        return i - start;
    }

    private void reverse(char[] chars, int start, int end) {
        while (start < end) {
            char tmp = chars[start];
            chars[start] = chars[end];
            chars[end] = tmp;
            start++;
            end--;
        }
    }
}
